function userShowLogoutButton()

{
	if ($('.ui-tabs-nav #logoutButton').length == 0) {
		// Création du bouton et ajout au DOM.
		var myLogoutButton = $('<li>');
		var myLogoutLink = $('<a>');
		myLogoutLink.attr('id', 'logoutButton');
		myLogoutLink.attr('href', '#');
		myLogoutLink.text('Se deconnecter');
		myLogoutButton.append(myLogoutLink);
		myLogoutButton.attr('class', 'ui-state-default ui-corner-top');
		$('.ui-tabs-nav').append(myLogoutButton).fadeIn();
		$('.ui-tabs-nav #logoutButton').click(function (myEvent) {
		    myEvent.preventDefault();
		    userLogout();
		    myRouter.setRoute('user/logout');
		    $(this).remove();
		    return false;
		});
	}
}


function userGetSessionDetails() {
    return {
        'Id': $.cookie('sessionId', userCookieSettings()),
        'UserName': $.cookie('sessionUserName', userCookieSettings()),
        'UserId': $.cookie('sessionUserId', userCookieSettings()),
        'UserEmail': $.cookie('sessionUserEmail', userCookieSettings())
    };
}


function userCookieSettings() 

{
	return {
		expires: 7, 
		path: '/',
        domain: '127.0.0.1'
	};
}


function userIsLogged() 

{
	return ($.cookie('sessionId') != null);
}


function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}



function eraseCookie(name) {
    createCookie(name, "", -1);
}


function userLogout() 

{
	if (userIsLogged()) {
	    var cookies = document.cookie.split(";");
	    for (var i = 0; i < cookies.length; i++)
	        eraseCookie(cookies[i].split("=")[0]);
        $('ul.ui-tabs-nav').hide();
	}
}


function userAuthRequired()

{
	if (!userIsLogged())
		myRouter.setRoute('user/login');
}


function userAuthForbidden()

{
	if (userIsLogged())
		myRouter.setRoute('home');
}


function userLogin(myUserId, myEmail, myUserName, myPassword) 

{
    if (!userIsLogged()) {
        if (CryptoJS.SHA512($('#loginUserPassword').val()).toString().toUpperCase() != myPassword)
            return false;
        $.cookie('sessionId', Math.floor(Math.random() * 45369), userCookieSettings());
        $.cookie('sessionUserId', myUserId, userCookieSettings());
		$.cookie('sessionUserName', myUserName, userCookieSettings());
		$.cookie('sessionUserEmail', myEmail, userCookieSettings());
        $('ul.ui-tabs-nav').show();
		userShowLogoutButton();
		return true;
	}
	return false;
}


$(document).ready(function () {
    if (userIsLogged())
        userShowLogoutButton();
	$('#loginFormErrors').hide();
	$('#registrationFormErrors').hide();
	$('#loginForm').submit(function(myEvent) {
		myEvent.preventDefault();
		$('#loginFormErrors').hide();
		$('#loginFormErrorList').children().remove();
		$.ajax({
			url: "/User/DetailsByName",
			type: 'GET',
			dataType: 'json', 
			data: {
				'userName': $('#loginUserName').val()
			},
			success: function(myData) {
			    if (userLogin(myData.Id, myData.Email, myData.UserName, myData.Password)) {
					myRouter.setRoute('home');
				} else {
					$('#loginFormErrorList').append('<li>Invalid login or password.</li>');
					$('#loginFormErrors').fadeIn();
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {
				$('#loginFormErrorList').append('<li>Impossible de se connecter au serveur.</li>');
				$('#loginFormErrors').fadeIn();
			}
		});
		return false;
	});
	$('#registrationForm').submit(function(myEvent) {
		myEvent.preventDefault();
		$('#registrationFormErrors').hide();
		$('#registrationFormErrorList').children().remove();
		$.ajax({
			url: "/User/Create",
			type: 'POST',
			dataType: 'json', 
			data: {
				'UserName': $('#regUserName').val(),
				'Password': $('#regUserPassword').val(),
                'Email': $('#regUserEmail').val(),
                'FirstName': $('#regUserFirstName').val(),
                'LastName': $('#regUserLastName').val(),
			},
			success: function(myData) {
                $.ajax({
			        url: "/User/DetailsByName",
			        type: 'GET',
			        dataType: 'json', 
			        data: {
			        	'userName': $('#regUserName').val()
			        },
			        success: function(myData) {
			            if (userLogin(myData.Id, myData.Email, myData.UserName, myData.Password)) {
			        		myRouter.setRoute('home');
			        	} else {
			        		$('#registrationFormErrorList').append("<li>Impossible de créer l'utilisateur spécifié.</li>");
			        		$('#registrationFormErrors').fadeIn();
			        	}
			        },
			        error: function(jqXHR, textStatus, errorThrown) {
			        	$('#registrationFormErrorList').append("<li>Impossible de créer l'utilisateur spécifié.</li>");
			        	$('#registrationFormErrors').fadeIn();
			        }
		        });
			},
			error: function(jqXHR, textStatus, errorThrown) {
				$('#registrationFormErrorList').append('<li>Impossible de se connecter au serveur.</li>');
				$('#registrationFormErrors').fadeIn();
			}
		});
		return false;
	});
	$('a#loginGoToRegistration').click(function(myEvent) {
		myEvent.preventDefault();
		$('#registrationFormErrors').hide();
		myRouter.setRoute('user/register');
		return false;
	});
	$('a.regGoToLogin').click(function(myEvent) {
		myEvent.preventDefault();
		$('#loginFormErrors').hide();
		myRouter.setRoute('user/login');
		return false;
	});
	$('a#logoutGoToLogin').click(function(myEvent) {
		myEvent.preventDefault();
		$('#loginFormErrors').hide();
		myRouter.setRoute('user/login');
		return false;
	});
});